import RPi.GPIO as GPIO
import dht11
from time import sleep, strftime
import matplotlib.pyplot as plt

# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

# read data using pin 16
instance = dht11.DHT11(pin = 16)

pltLength = 30
#Turn the interactive mode on.
plt.ion()


# index 
x = [i for i in range(pltLength)]
# value
t = [None for i in range(pltLength)]
h = [None for i in range(pltLength)]
i = 0


def write_value(Temperature,Humidity):
    with open("Temperature.csv", "a") as log:
        log.write("{0},{1},{2}\n".format(strftime("%Y-%m-%d %H:%M:%S"), str(Temperature),str(Humidity)))

def graph(Temperature,Humidity):
    global i
    if i < pltLength:
        t[i] = Temperature
        h[i] = Humidity
    
        i += 1
    else:
        # Once enough data is captured, append the newest data point and delete the oldest
        t.append(Temperature)
        h.append(Humidity)
        del t[0]
        del h[0]
        
    # clear the current figure.
    plt.clf()
    plt.title("DHT11")
    plt.xlim(0, pltLength)
    plt.plot(x, t, "r-o",label="Temperature C")
    plt.plot(x, h, "b-*",label="Humidity %")
    plt.draw()
    plt.legend()
    plt.pause(0.1)


while True:
    try:
        result = instance.read()

        if result.is_valid():
            Temperature=result.temperature
            Humidity=result.humidity
            write_value(Temperature,Humidity)
            graph(Temperature,Humidity)
        else:
            pass
        sleep(1)    
    except KeyboardInterrupt:
          # 使用结束，释放引脚
        GPIO.cleanup()
        break        
